package com.lxs.task001;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorExample {
    public static void main(String[] args) {
        // 创建调度线程池
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        // 创建任务
        Runnable task = () -> {
            System.out.println("定时任务执行: " + java.time.LocalTime.now());
        };

        // 调度任务
        // 延迟1秒后开始执行，每隔2秒执行一次
        ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(task, 1, 2, TimeUnit.SECONDS);

        // 10秒后取消任务并关闭调度器
        scheduler.schedule(() -> {
            future.cancel(true);
            scheduler.shutdown();
            System.out.println("定时任务已停止");
        }, 10, TimeUnit.SECONDS);
    }
}
